$(function () {
    let id = localStorage.getItem("userId");
    // sessionStorage.getItem("userId");
    // $.cookie("userId");
    findById(id);
})

function findById(id) {
    console.log(id);
    $.ajax({
        url: '/back/user/findById',
        data: {id: id},
        dataType: 'json',
        type: "get",
        success: function (data) {
            setData(data.userModel);
        }
    })
}

function setData(data) {
    $("#username").val(data.username);
    $("#phone").val(data.phone);
    $("input[name='sex'][value=" + data.sex + "]").attr("checked", true);
    $("#birthday").val(data.birthday);
    setaihao(data.hobby);
    $("#introduce").val(data.introduce);

}

function setaihao(hobby) {
    hobby.replace("[", '').replace("]", "");
    hobby = hobby.split(",");
    $("input:checkbox[name='hobby']").each(function () {
        for (let i = 0; i < hobby.length; i++) {
            console.log($.trim(hobby[i]) + "+++++++++++++" + $(this).val());
            if ($(this).val() == $.trim(hobby[i])) {
                $(this).attr("checked", true);
            }
        }
    })
}

function clearAll() {
    // $("#username").val("");
    $("#phone").val("");
    $("input[name='sex']").attr("checked", false);
    $("#birthday").val("");
    clearAaihao();
    $("#introduce").val("");

}

function clearAaihao() {
    $("input:checkbox[name='hobby']").each(function () {
        $(this).attr("checked", false);
    })
}

function save() {
    // if (judge()) {
    //只有judge（）为true的时候，我们才去访问后台
    //js对象
    //js数据类型 字符 数字 数组  对象 布尔
    //对象  json
    let data = {
        id:localStorage.getItem("userId"),
        username: $("#username").val(),
        password: document.getElementById("password").value,
        code: $("#code").val(),
        phone: $("#phone").val(),
        sex: $("input[name='sex']:checked").val(),
        birthday: $("#birthday").val(),
        hobby: JSON.stringify(aihao()),
        introduce: $("#introduce").val()
    };

    $.ajax({
        url: '/back/user/update',//地址，链接后台的地址
        type: 'post',//方法类型
        data: data,//传递到后台的数据
        dataType: 'json',//后端传递给前端的数据类型text文本或者json对象   application  html
        success: function (data) {//data是后台传递到前端的值
            if (data.result == 1) {
                $('#right').load('/html/back/user/userManage.html');
            } else {
                alert("修改失败");
            }
        }
    })
    // }

}


function aihao() {
    let hb = [];
    $("input:checkbox[name='hobby']").each(function () {
        if ($(this).prop("checked")) {
            hb.push($(this).val());
        }
    })
    return hb;
}